package com.lbj.mall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbj.mall.common.entity.vo.GiteeVo;
import com.lbj.mall.common.utils.PageUtils;
import com.lbj.mall.common.utils.Query;
import com.lbj.mall.member.dao.MemberDao;
import com.lbj.mall.member.entity.MemberEntity;
import com.lbj.mall.member.entity.MemberLevelEntity;
import com.lbj.mall.member.entity.vo.MemberLoginVo;
import com.lbj.mall.member.entity.vo.MemberRegisterVo;
import com.lbj.mall.member.exception.EmailExistException;
import com.lbj.mall.member.exception.UsernameExistException;
import com.lbj.mall.member.service.MemberLevelService;
import com.lbj.mall.member.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo registerVo) {
        MemberEntity member = new MemberEntity();

        // 检测用户名是否存在，抛出异常
        String username = registerVo.getUsername();
        checkUsernameExist(username);
        member.setUsername(username);
        member.setNickname(username);

        // 检测邮箱是否存在，抛出异常
        checkEmailExist(registerVo.getEmail());
        member.setEmail(registerVo.getEmail());

        // 设置默认的会员等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevelInfo();
        member.setLevelId(levelEntity.getId());

        // 设置用户密码，保存密文
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(registerVo.getPassword());
        member.setPassword(encode);
        baseMapper.insert(member);
    }

    @Override
    public void checkUsernameExist(String username) throws UsernameExistException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("username", username));
        if (count > 0) throw new UsernameExistException();
    }

    @Override
    public void checkEmailExist(String email) throws EmailExistException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("email", email));
        if (count > 0) throw new EmailExistException();
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String account = loginVo.getAccount();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", account).or().eq("email", account));
        if (entity == null) return null;
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(loginVo.getPassword(), entity.getPassword());
        if (!matches) return null;
        return entity;
    }

    @Override
    public MemberEntity giteeLogin(GiteeVo giteeVo) {


        // 查询数据库判断用户是否第一次登录，如果第一次登录则插入数据，如果不是第一次则更新数据
        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("gitee_id", giteeVo.getGiteeId()));
        if (member == null) {
            // 用户第一次登录
            member = new MemberEntity();
            member.setHeader(giteeVo.getHeader());
            member.setCreateTime(new Date());
            MemberLevelEntity levelEntity = memberLevelService.getDefaultLevelInfo();
            member.setLevelId(levelEntity.getId());
            member.setNickname(giteeVo.getNickname());
            member.setGender(1);
            member.setGiteeId(giteeVo.getGiteeId());
            baseMapper.insert(member);
        }

        return member;
    }
}